//
//  RMMLongingViewController.m
//  Romomo
//
//  Created by puman on 16/10/18.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "RMMLongingViewController.h"
#import "RMMPasswordLoginView.h"
#import "RMMNoPasswordViewController.h"
#import "RMMProtocolViewController.h"

@interface RMMLongingViewController ()<UITextFieldDelegate>

@property (strong, nonatomic) NSString *loginType; // 登陆类型
@property (strong, nonatomic) NSDictionary *userDic;

@end

@implementation RMMLongingViewController
{
    RMMPasswordLoginView *_loginView;
    NSString *_mobile;
    NSString *_openid;
    NSString *_password;
    NSInteger _number;
    NSString *_yanCode;
}
- (void)dealloc{
    NS_REM(@"AGREELOGIN", nil);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self addViews];
    // Do any additional setup after loading the view.
}
- (void)addViews{
    self.view.backgroundColor = kWhiteColor;
    self.navigationItem.title = @"登录容么么";
    [self addLeftItem];
    _loginType = @"1";
    _mobile = @"";
    _password = @"";
    _openid = @"";
    _number = 60;
    _loginView = [[RMMPasswordLoginView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _loginView.userName.delegate = self;
    _loginView.password.delegate = self;
    TEXTFIELD_S(_loginView.userName, beginLanding:);
    TEXTFIELD_S(_loginView.password, beginLanding:);
    _loginView.userName.keyboardType = UIKeyboardTypeNumberPad;
    _loginView.password.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    BUTTON_S(_loginView.loginBut, loginButClick);
    BUTTON_S(_loginView.sendBut, sendButMessageClick);
    [self.view addSubview:_loginView];
    for (int i = 0; i < 1; i++) {
        UIButton *button = [self.view viewWithTag:10 + i];
        BUTTON_S(button, thridLongin:);
    }
    BUTTON_S(_loginView.procotolBut, procotolButtClick);
    
}
- (void)procotolButtClick{
    [self.navigationController pushViewController:[[RMMProtocolViewController alloc] init] animated:YES];
}
- (void)addLeftItem{
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:(UIBarButtonItemStylePlain) target:self action:@selector(cancel)];
    self.navigationItem.leftBarButtonItem = item;
   // item.tintColor = COLORFROMCODE(0x9B9B9B1, 1);
}
- (void)cancel{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)thridLongin:(UIButton *)button{
    if (button.tag == 10) {
        RMMNoPasswordViewController *VC = [[RMMNoPasswordViewController alloc] init];
        [self.navigationController pushViewController:VC animated:YES];
    } else if (button.tag == 11) {
        [self useWeiXinLogin];
    } else {
        [self useQQLogin];
    }
}
// QQ登陆
- (void)useQQLogin{
    [[UMSocialManager defaultManager] authWithPlatform:UMSocialPlatformType_QQ currentViewController:nil completion:^(id result, NSError *error) {
        if (error) {
            
        } else {
            UMSocialUserInfoResponse *response = result;
            _loginType = @"3";
            _openid = response.openid;
            [RMMFileManager shareHandle].loginType = @"3";
            [RMMFileManager shareHandle].openid = response.openid;
            [self loginRequestWith:_loginType];
        }
    }];
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_QQ currentViewController:nil completion:^(id result, NSError *error) {
        if (error) {
            
        } else {
            UMSocialUserInfoResponse *resp = result;
            _userDic = @{@"NAME":resp.name,@"IMAGE_URL":resp.iconurl,@"GENDER":resp.gender};
        }
        
    }];
}
// 微信
- (void)useWeiXinLogin{
    [[UMSocialManager defaultManager] authWithPlatform:UMSocialPlatformType_WechatSession currentViewController:nil completion:^(id result, NSError *error) {
        if (error) {
            
        } else {
            UMSocialAuthResponse *resp = result;
            
            // 授权信息
            NSLog(@"Wechat uid: %@", resp.uid);
            NSLog(@"Wechat openid: %@", resp.openid);
            NSLog(@"Wechat accessToken: %@", resp.accessToken);
            NSLog(@"Wechat refreshToken: %@", resp.refreshToken);
            NSLog(@"Wechat expiration: %@", resp.expiration);
            _loginType = @"2";
            _openid = resp.openid;
            [RMMFileManager shareHandle].loginType = @"2";
            [RMMFileManager shareHandle].openid = resp.openid;
            [self loginRequestWith:_loginType];
            // 第三方平台SDK源数据
            NSLog(@"Wechat originalResponse: %@", resp.originalResponse);
        }
    }];
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:nil completion:^(id result, NSError *error) {
        if (error) {
            
        } else {
            UMSocialUserInfoResponse *resp = result;
            
            // 授权信息
            NSLog(@"Wechat uid: %@", resp.uid);
            NSLog(@"Wechat openid: %@", resp.openid);
            NSLog(@"Wechat accessToken: %@", resp.accessToken);
            NSLog(@"Wechat refreshToken: %@", resp.refreshToken);
            NSLog(@"Wechat expiration: %@", resp.expiration);
            
            // 用户信息
            NSLog(@"Wechat name: %@", resp.name);
            _userDic = @{@"NAME":resp.name,@"IMAGE_URL":resp.iconurl,@"GENDER":resp.gender};
            // 第三方平台SDK源数据
            NSLog(@"Wechat originalResponse: %@", resp.originalResponse);
        }
    }];
}
- (void)beginLanding:(UITextField *)text{
    if (_loginView.userName.text.length != 0) {
        if ([[_loginView.sendBut titleForState:(UIControlStateNormal)] isEqualToString:@"收取验证码"]) {
            [self butOpen:_loginView.sendBut];
        }
        if (_loginView.password.text.length != 0) {
            _loginView.loginBut.layer.borderColor = kBasicColor.CGColor;
            [_loginView.loginBut setTitleColor:kBasicColor forState:(UIControlStateNormal)];
            _loginView.loginBut.userInteractionEnabled = YES;
        } else {
            _loginView.loginBut.layer.borderColor = COLORFROMCODE(0xF3F2F3 , 1).CGColor;
            [_loginView.loginBut setTitleColor:COLORFROMCODE(0xD7D7D7, 1) forState:(UIControlStateNormal)];
            _loginView.loginBut.userInteractionEnabled = NO;
        }
    } else {
        _loginView.loginBut.layer.borderColor = COLORFROMCODE(0xF3F2F3 , 1).CGColor;
        [_loginView.loginBut setTitleColor:COLORFROMCODE(0xD7D7D7, 1) forState:(UIControlStateNormal)];
        _loginView.loginBut.userInteractionEnabled = NO;
        if ([[_loginView.sendBut titleForState:(UIControlStateNormal)] isEqualToString:@"收取验证码"]) {
            [self butOff:_loginView.sendBut];
        }
    }
    if (text == _loginView.userName) {
        if (_loginView.userName.text.length > 11) {
            _loginView.userName.text = [_loginView.userName.text substringToIndex:11];
        }
    }
}
// 登陆
- (void)loginButClick{
    [self.view endEditing:YES];
    if (![RMMFileManager isPhoneNumberWith:_loginView.userName.text]) {
        [RMMFileManager MBProgressWith:@"手机号码格式错误!" onView:self.view];
        return;
    }
    [self loginRequestWith:@"0"];
}
// 发送验证码
- (void)sendButMessageClick{
    if (![RMMFileManager isPhoneNumberWith:_loginView.userName.text]) {
        [RMMFileManager MBProgressWith:@"手机号码输入错误!" onView:self.view];
        return;
    }
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"mobile"] = _loginView.userName.text;
    NSString *url = SendMessageUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            _yanCode = dataDic[@"data"];
            [_loginView.userName resignFirstResponder];
            [self countDown];
            [RMMFileManager MBProgressWith:@"验证码发送成功!" onView:self.view];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
        
    } error:^(NSError *errors) {
        
    } view:self.view];
}
// 倒计时
- (void)countDown{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer:) userInfo:@"倒计时" repeats:YES];
    [self butOff:_loginView.sendBut];
    [timer fire];
    
}
- (void)timer:(NSTimer *)timer{
    if (_number == 0) {
        [timer invalidate];
        [_loginView.sendBut setTitle:@"收取验证码" forState:(UIControlStateNormal)];;
        _number = 60;
        [self butOpen:_loginView.sendBut];
    } else {
        [_loginView.sendBut setTitle:[NSString stringWithFormat:@"%ld秒后重新收取",_number] forState:(UIControlStateNormal)];
        _number--;
    }
}

- (void)butOpen:(UIButton *)button{
    button.backgroundColor = kBasicColor;
    [button setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
    button.userInteractionEnabled = YES;
}
- (void)butOff:(UIButton *)button{
    button.backgroundColor = RGBA(238, 238, 238, 1);
    [button setTitleColor:COLORFROMCODE(0xD7D7D7, 1) forState:(UIControlStateNormal)];
    button.userInteractionEnabled = NO;
}

// 登陆网络请求
- (void)loginRequestWith:(NSString *)loginType{
    [self.view endEditing:YES];
    if (_loginView.userName.text.length) {
        _mobile = _loginView.userName.text;
    }
    if ([loginType isEqualToString:@"0"]) {
        if (![_yanCode isEqualToString:_loginView.password.text]) {
            [RMMFileManager MBProgressWith:@"验证码输入输入错误!" onView:self.view];
            return;
        }
    }
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"org_no"] = Org_no;
    parDic[@"login_type"] = loginType;
    parDic[@"mobile"] = _mobile;
    parDic[@"openid"] = _openid;
    parDic[@"password"] = _password;
    NSString *url = [NSString stringWithFormat:@"%@",LogingUrl];
    [OSRequestManager requestFWithUrlString:url parDic:parDic method:POST finish:^(NSDictionary *dataDic) {
        [RMMFileManager shareHandle].userDic = [RMMFileManager setValueForDic:dataDic[@"data"]];
        [RMMFileManager shareHandle].isLoginSuccess = YES;
        [RMMFileManager MBProgressWith:@"登录成功!" onView:self.view];
        [[RMMFileManager shareHandle] saveVale:@"0" forKey:@"SHOPMARTCOUNT"];
        [[RMMFileManager shareHandle] saveVale:[NSString stringWithFormat:@"%@",dataDic[@"data"][@"CUST_ID"]] forKey:@"CUST_ID"];
        NS_POST(@"LANDSUCESS", nil, nil);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });

    } error:^(NSError *errors) {
        
    } view:self.view];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
